//
//  JDRefreshControl.swift
//  JDWeiBo
//
//  Created by apple on 15/7/6.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

class JDRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        addSubview(refreshView)
        
        // 设置自动布局
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        
        // KVO 监听 自己
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    // 取消监听
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    // 显示图标，标记
    private var showTipFlag = false
    
    // 正在加载标记
    private var loadingFlag = false
    

    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        print(frame)
        
        // 如果正在加载数据，就显示加载动画
        if refreshing && !loadingFlag {
            refreshView.startLoadingAnim()
            loadingFlag = true
            return
        }
        
        // 下拉旋转度数
        if frame.origin.y < -50 && !showTipFlag {
            showTipFlag = true
            refreshView.rotateTipIcon(showTipFlag)
        } else if frame.origin.y >= -50 && showTipFlag {
            showTipFlag = false
            refreshView.rotateTipIcon(showTipFlag)
        }
}

    
    // 设置动画
    override func endRefreshing() {
        super.endRefreshing()
        ///  关闭动画
        refreshView.stopLoadingAnim()
        /// 刷新标记
        loadingFlag = false
    }
    
    // 懒加载控件
    lazy var refreshView = JDRefreshView.refreshView()
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

/// 刷新视图类
class JDRefreshView : UIView {
    // 正在刷新图标
    @IBOutlet weak var loadingIcon: UIImageView!
    // 遮盖View
    @IBOutlet weak var tipView: UIView!
    // 下拉图片
    @IBOutlet weak var tipIcon: UIImageView!
    
    class func refreshView() -> JDRefreshView {
        
        return NSBundle.mainBundle().loadNibNamed("JDRefreshView", owner: nil, options: nil).last as! JDRefreshView
    }
    
    // 旋转展示图标
    private func rotateTipIcon(clockWise : Bool) {
        
        var angle = M_PI
        // 顺势针转场，给点差度特性会反转
        angle += clockWise ? -0.01 : 0.01
    
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    }
    
    // 开启加速动画
    private func startLoadingAnim() {
        // 隐藏遮盖View
        tipView.hidden = true
        // 设置动画模式
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        // loadingIcon加载动画
        loadingIcon.layer.addAnimation(anim, forKey: nil)
    }
    // 停止动画
    private func stopLoadingAnim() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
}